<?php
declare(strict_types=1);

namespace SixShop\Eav\Controller;

use SixShop\Core\Request;
use SixShop\Eav\Entity\EavValueEntity;
use SixShop\Eav\Model\EavAttributeModel;
use think\Response;

use function SixShop\Core\error_response;
use function SixShop\Core\success_response;

class ValueController
{
    /**
     * 查询指定实体的所有属性值
     * GET /eav/value?entity_id=123&entity_type_id=1
     */
    public function index(Request $request, EavValueEntity $entity): Response
    {
        $entityId = $request->get('entity_id/d');
        $entityTypeId = $request->get('entity_type_id/d');
        if (!$entityId) {
            return error_response('缺少实体ID');
        }
        if (!$entityTypeId) {
            return error_response('缺少实体类型ID');
        }
        // 查询该实体的所有属性值
        $list = $entity->where([
            'entity_id' => $entityId,
            'entity_type_id' => $entityTypeId,
        ])->with(['attribute' => function ($query) {
            $query->with(['option_list']);
        }])->select();
        return success_response($list);
    }

    /**
     * 保存/更新指定实体的属性值
     * POST /eav/value
     * body: [
     *   { "entity_id": 123, "entity_type_id": 1, "attribute_id": 2, "value": "红色" }
     * ]
     */
    public function save(Request $request, EavValueEntity $entity): Response
    {
        $data = $request->post();
        if (empty($data) || !is_array($data)) {
            return error_response('参数错误');
        }
        // 支持批量写入
        foreach ($data as $item) {
            if (
                empty($item['entity_id']) ||
                empty($item['entity_type_id']) ||
                empty($item['attribute_id']) ||
                !isset($item['value'])
            ) {
                continue;
            }
            // 获取属性类型
            $attr = EavAttributeModel::find($item['attribute_id']);
            if (!$attr) {
                continue;
            }
            $saveData = [
                'entity_id'    => $item['entity_id'],
                'entity_type_id' => $item['entity_type_id'],
                'attribute_id' => $item['attribute_id'],
            ];
            switch ($attr->backend_type) {
                case 'int':
                    $saveData['value_int'] = intval($item['value']);
                    break;
                case 'decimal':
                    $saveData['value_decimal'] = floatval($item['value']);
                    break;
                case 'text':
                    $saveData['value_text'] = $item['value'];
                    break;
                case 'varchar':
                default:
                    $saveData['value_varchar'] = $item['value'];
            }
            // 先查找是否已存在，存在则更新，否则新增
            $exist = $entity->where([
                'entity_id' => $item['entity_id'],
                'entity_type_id' => $item['entity_type_id'],
                'attribute_id' => $item['attribute_id']
            ])->find();
            if ($exist) {
                $entity->where('id', $exist['id'])->update($saveData);
            } else {
                $entity->save($saveData);
            }
        }
        return success_response('保存成功');
    }

    /**
     * 删除指定实体的所有属性值
     * DELETE /eav/value?entity_id=123&entity_type_id=1
     */
    public function delete(Request $request, EavValueEntity $entity): Response
    {
        $entityId = $request->get('entity_id/d');
        $entityTypeId = $request->get('entity_type_id/d');
        if (!$entityId || !$entityTypeId) {
            return error_response('参数缺失');
        }
        $entity->where(['entity_id' => $entityId, 'entity_type_id' => $entityTypeId])->delete();
        return success_response('删除成功');
    }
}
